package com.chis.netty.http.server;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chis.bean.EpAccessTokenBean;
import com.chis.bean.EpGeneralContentBean;
import com.chis.bean.EpSendMsgTextBean;

import com.chis.netty.http.test.sms.smsServer.SmsServerProxy;
import com.chis.util.MD5Util;
import com.chis.utils.EpWxUtil;
import com.chis.utils.PropUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.net.util.Base64;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.zip.GZIPOutputStream;

/**
 * 
 * @Description 
 * @Company zwx
 * @author wlj
 * @version 2019年12月19日
 */
public class HttpServerHandler extends ChannelInboundHandlerAdapter {

    private String result = "";

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (!(msg instanceof FullHttpRequest)) {
            result = "未知请求!";
            send(ctx, result, HttpResponseStatus.BAD_REQUEST);
            return;
        }
        FullHttpRequest httpRequest = (FullHttpRequest) msg;
        try {
            String path = httpRequest.uri();          //获取路径 uri路径,可以根据 这个判断请求接口
            String body = getBody(httpRequest);     //获取参数
            HttpMethod method = httpRequest.method();//获取请求方法
            System.out.println("接收到:" + method + " 请求:"+path);
            //如果是GET请求
            if (HttpMethod.GET.equals(method)) {
                //接受到的消息，做业务逻辑处理...
                send(ctx, result, HttpResponseStatus.BAD_REQUEST);
                return;
            }
            //如果是POST请求
            if (HttpMethod.POST.equals(method)) {
                //接受到的消息，做业务逻辑处理...
                try {
                    System.out.println("报警： "+body);
                    JSONObject jsonObject = JSON.parseObject(body);
                    String alerts = jsonObject.getString("alerts");
                    JSONArray jsonArray = JSON.parseArray(alerts);
                    jsonArray.forEach(jsonobejct -> sendmsg((JSONObject)jsonobejct));
                    result = handresp();
                } catch (Exception e){
                    e.printStackTrace();
                    result = handrespFail(e.getMessage());
                }
                send(ctx, result, HttpResponseStatus.OK);
            }
        } catch (Exception e) {
            System.out.println("处理请求失败!");
            e.printStackTrace();
        } finally {
            //释放请求
            httpRequest.release();
        }
    }

    private void sendmsg(JSONObject jsonobejct) {
        StringBuffer sBuffer = new StringBuffer();
        String status = (String) jsonobejct.get("status");
        if(status.equals("firing")){
            sBuffer.append("【报警】");
        } else if(status.equals("resolved")){
            sBuffer.append("【恢复】");
        }
        String date = (String) jsonobejct.get("startsAt");
        sBuffer.append("【").append(date.substring(0,19)).append("】");
        JSONObject annotations = (JSONObject) jsonobejct.get("annotations");
        sBuffer.append(annotations);

        //短信预警
        sendmymsg(sBuffer.toString());
        //微信预警
        sendmywx(sBuffer.toString());
    }

    /**
     *
     * @param content
     */
    public void sendmywx(String content) {
        if(!Boolean.parseBoolean(PropUtil.getproval("alert.server.wx.able"))){
            return;
        }
        try {
            EpAccessTokenBean token = EpWxUtil.selecToken("eptoken");
            if (token == null) {
                token = EpWxUtil.createToken("eptoken");
            }
            // 主动发送消息
            if(content.length()>600){
                content=content.substring(0, 600);
            }
            EpSendMsgTextBean text = new EpSendMsgTextBean();
            // 成员ID列表
            text.setTouser("@all");
            text.setMsgtype("text");
            text.setAgentid("3");
            text.setText(new EpGeneralContentBean(content));
            int res = EpWxUtil.sendMessage(token.getToken(), text);
            System.out.println("微信推送："+res);

        } catch (Exception e1) {
            e1.printStackTrace();

        }
    }

    /**
     *
     * @param content
     */
    public void sendmymsg(String content) {
        if(!Boolean.parseBoolean(PropUtil.getproval("alert.server.msg.able"))){
            return;
        }
        String sendUrl = PropUtil.getproval("alert.server.msg.url");
        String username = PropUtil.getproval("alert.server.msg.usr");
        String password = PropUtil.getproval("alert.server.msg.psd");
        String phoneNum = PropUtil.getproval("alert.server.msg.rec");
        String sign = "";
        SmsServerProxy proxy = new SmsServerProxy(sendUrl);

        StringBuilder sb = new StringBuilder();
        if(StringUtils.isNotBlank(phoneNum) && StringUtils.isNotBlank(content)) {
            sb.append("<?xml version='1.0' encoding='GB2312'?>");
            sb.append("<SmsInfoes>");
            for (String phone : phoneNum.split(",")) {
                sb.append("<SmsInfo>");
                sb.append("<UserCode>").append(username).append("</UserCode>");
                sb.append("<TelNum>").append(phone).append("</TelNum>");
                sb.append("<Content>").append(content).append("</Content>");
                sb.append("<Count>1</Count>");
                sb.append("<InvalidDate>").append("2020-07-25 00:00:00").append("</InvalidDate>");
                sb.append("<SpTag>0</SpTag>");

                sb.append("<Sign>").append(sign).append("</Sign>");
                sb.append("<SystemMark>12</SystemMark>");
                sb.append("<IsNight>1</IsNight>");
                sb.append("<NetTag>1</NetTag>");
                sb.append("</SmsInfo>");
            }
            sb.append("</SmsInfoes>");
            try {
                int rst = proxy.smsUpLoad(compress(sb.toString()), username, new MD5Util().getMD5ofStr(password).toLowerCase());
                System.out.println("短信推送："+rst);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private String compress(String s) {
        try {
            ByteArrayInputStream input = new ByteArrayInputStream(s.getBytes("GBK"));
            ByteArrayOutputStream output = new ByteArrayOutputStream(1024);
            GZIPOutputStream gzout = new GZIPOutputStream(output);

            byte[] buf = new byte[1024];
            int number;

            while ((number = input.read(buf)) != -1) {
                gzout.write(buf, 0, number);
            }

            gzout.close();
            input.close();
            String result = Base64.encodeBase64String(output.toByteArray());
            output.close();
            return result;
        } catch (IOException e) {

        }
        return null;
    }


    public static void main(String[] args) {
        String s = "{\"receiver\":\"webhook\",\"status\":\"firing\",\"alerts\":[{\"status\":\"firing\",\"labels\":{\"alertname\":\"node-up\",\"instance\":\"10.88.88.118:9591\",\"job\":\"non-k8s/node_export\",\"prometheus\":\"monitoring/k8s\",\"severity\":\"1\",\"team\":\"node\"},\"annotations\":{\"summary\":\"10.88.88.118:9591 已停止运行超过 15s！\"},\"startsAt\":\"2020-08-05T01:17:42.81696489Z\",\"endsAt\":\"0001-01-01T00:00:00Z\",\"generatorURL\":\"http://prometheus-k8s-0:9090/graph?g0.expr=up%7Bjob%3D%22non-k8s%2Fnode_export%22%7D+%3D%3D+0\\u0026g0.tab=1\"},{\"status\":\"firing\",\"labels\":{\"alertname\":\"node-up\",\"instance\":\"10.88.88.137:9591\",\"job\":\"non-k8s/node_export\",\"prometheus\":\"monitoring/k8s\",\"severity\":\"1\",\"team\":\"node\"},\"annotations\":{\"summary\":\"10.88.88.137:9591 已停止运行超过 15s！\"},\"startsAt\":\"2020-08-05T01:17:42.81696489Z\",\"endsAt\":\"0001-01-01T00:00:00Z\",\"generatorURL\":\"http://prometheus-k8s-0:9090/graph?g0.expr=up%7Bjob%3D%22non-k8s%2Fnode_export%22%7D+%3D%3D+0\\u0026g0.tab=1\"},{\"status\":\"firing\",\"labels\":{\"alertname\":\"node-up\",\"instance\":\"10.88.88.138:9591\",\"job\":\"non-k8s/node_export\",\"prometheus\":\"monitoring/k8s\",\"severity\":\"1\",\"team\":\"node\"},\"annotations\":{\"summary\":\"10.88.88.138:9591 已停止运行超过 15s！\"},\"startsAt\":\"2020-08-05T01:17:42.81696489Z\",\"endsAt\":\"0001-01-01T00:00:00Z\",\"generatorURL\":\"http://prometheus-k8s-0:9090/graph?g0.expr=up%7Bjob%3D%22non-k8s%2Fnode_export%22%7D+%3D%3D+0\\u0026g0.tab=1\"},{\"status\":\"firing\",\"labels\":{\"alertname\":\"node-up\",\"instance\":\"10.88.88.139:9591\",\"job\":\"non-k8s/node_export\",\"prometheus\":\"monitoring/k8s\",\"severity\":\"1\",\"team\":\"node\"},\"annotations\":{\"summary\":\"10.88.88.139:9591 已停止运行超过 15s！\"},\"startsAt\":\"2020-08-05T01:18:12.81696489Z\",\"endsAt\":\"0001-01-01T00:00:00Z\",\"generatorURL\":\"http://prometheus-k8s-1:9090/graph?g0.expr=up%7Bjob%3D%22non-k8s%2Fnode_export%22%7D+%3D%3D+0\\u0026g0.tab=1\"},{\"status\":\"firing\",\"labels\":{\"alertname\":\"node-up\",\"instance\":\"10.88.88.156:9591\",\"job\":\"non-k8s/node_export\",\"prometheus\":\"monitoring/k8s\",\"severity\":\"1\",\"team\":\"node\"},\"annotations\":{\"summary\":\"10.88.88.156:9591 已停止运行超过 15s！\"},\"startsAt\":\"2020-08-05T01:18:12.81696489Z\",\"endsAt\":\"0001-01-01T00:00:00Z\",\"generatorURL\":\"http://prometheus-k8s-1:9090/graph?g0.expr=up%7Bjob%3D%22non-k8s%2Fnode_export%22%7D+%3D%3D+0\\u0026g0.tab=1\"},{\"status\":\"firing\",\"labels\":{\"alertname\":\"node-up\",\"instance\":\"10.88.88.159:9591\",\"job\":\"non-k8s/node_export\",\"prometheus\":\"monitoring/k8s\",\"severity\":\"1\",\"team\":\"node\"},\"annotations\":{\"summary\":\"10.88.88.159:9591 已停止运行超过 15s！\"},\"startsAt\":\"2020-08-05T01:18:12.81696489Z\",\"endsAt\":\"0001-01-01T00:00:00Z\",\"generatorURL\":\"http://prometheus-k8s-1:9090/graph?g0.expr=up%7Bjob%3D%22non-k8s%2Fnode_export%22%7D+%3D%3D+0\\u0026g0.tab=1\"},{\"status\":\"resolved\",\"labels\":{\"alertname\":\"node-up\",\"instance\":\"10.88.88.166:9591\",\"job\":\"non-k8s/node_export\",\"prometheus\":\"monitoring/k8s\",\"severity\":\"1\",\"team\":\"node\"},\"annotations\":{\"summary\":\"10.88.88.166:9591 已停止运行超过 15s！\"},\"startsAt\":\"2020-08-05T01:17:42.81696489Z\",\"endsAt\":\"2020-08-05T01:28:12.81696489Z\",\"generatorURL\":\"http://prometheus-k8s-0:9090/graph?g0.expr=up%7Bjob%3D%22non-k8s%2Fnode_export%22%7D+%3D%3D+0\\u0026g0.tab=1\"},{\"status\":\"firing\",\"labels\":{\"alertname\":\"node-up\",\"instance\":\"10.88.88.167:9591\",\"job\":\"non-k8s/node_export\",\"prometheus\":\"monitoring/k8s\",\"severity\":\"1\",\"team\":\"node\"},\"annotations\":{\"summary\":\"10.88.88.167:9591 已停止运行超过 15s！\"},\"startsAt\":\"2020-08-05T01:18:12.81696489Z\",\"endsAt\":\"0001-01-01T00:00:00Z\",\"generatorURL\":\"http://prometheus-k8s-1:9090/graph?g0.expr=up%7Bjob%3D%22non-k8s%2Fnode_export%22%7D+%3D%3D+0\\u0026g0.tab=1\"},{\"status\":\"firing\",\"labels\":{\"alertname\":\"node-up\",\"instance\":\"10.88.88.168:9591\",\"job\":\"non-k8s/node_export\",\"prometheus\":\"monitoring/k8s\",\"severity\":\"1\",\"team\":\"node\"},\"annotations\":{\"summary\":\"10.88.88.168:9591 已停止运行超过 15s！\"},\"startsAt\":\"2020-08-05T01:18:12.81696489Z\",\"endsAt\":\"0001-01-01T00:00:00Z\",\"generatorURL\":\"http://prometheus-k8s-1:9090/graph?g0.expr=up%7Bjob%3D%22non-k8s%2Fnode_export%22%7D+%3D%3D+0\\u0026g0.tab=1\"},{\"status\":\"firing\",\"labels\":{\"alertname\":\"node-up\",\"instance\":\"10.88.88.169:9591\",\"job\":\"non-k8s/node_export\",\"prometheus\":\"monitoring/k8s\",\"severity\":\"1\",\"team\":\"node\"},\"annotations\":{\"summary\":\"10.88.88.169:9591 已停止运行超过 15s！\"},\"startsAt\":\"2020-08-05T01:17:42.81696489Z\",\"endsAt\":\"0001-01-01T00:00:00Z\",\"generatorURL\":\"http://prometheus-k8s-0:9090/graph?g0.expr=up%7Bjob%3D%22non-k8s%2Fnode_export%22%7D+%3D%3D+0\\u0026g0.tab=1\"},{\"status\":\"firing\",\"labels\":{\"alertname\":\"node-up\",\"instance\":\"10.88.88.175:9591\",\"job\":\"non-k8s/node_export\",\"prometheus\":\"monitoring/k8s\",\"severity\":\"1\",\"team\":\"node\"},\"annotations\":{\"summary\":\"10.88.88.175:9591 已停止运行超过 15s！\"},\"startsAt\":\"2020-08-05T01:18:12.81696489Z\",\"endsAt\":\"0001-01-01T00:00:00Z\",\"generatorURL\":\"http://prometheus-k8s-1:9090/graph?g0.expr=up%7Bjob%3D%22non-k8s%2Fnode_export%22%7D+%3D%3D+0\\u0026g0.tab=1\"},{\"status\":\"firing\",\"labels\":{\"alertname\":\"node-up\",\"instance\":\"10.88.88.177:9591\",\"job\":\"non-k8s/node_export\",\"prometheus\":\"monitoring/k8s\",\"severity\":\"1\",\"team\":\"node\"},\"annotations\":{\"summary\":\"10.88.88.177:9591 已停止运行超过 15s！\"},\"startsAt\":\"2020-08-05T01:18:12.81696489Z\",\"endsAt\":\"0001-01-01T00:00:00Z\",\"generatorURL\":\"http://prometheus-k8s-1:9090/graph?g0.expr=up%7Bjob%3D%22non-k8s%2Fnode_export%22%7D+%3D%3D+0\\u0026g0.tab=1\"},{\"status\":\"firing\",\"labels\":{\"alertname\":\"node-up\",\"instance\":\"10.88.88.179:9591\",\"job\":\"non-k8s/node_export\",\"prometheus\":\"monitoring/k8s\",\"severity\":\"1\",\"team\":\"node\"},\"annotations\":{\"summary\":\"10.88.88.179:9591 已停止运行超过 15s！\"},\"startsAt\":\"2020-08-05T01:17:42.81696489Z\",\"endsAt\":\"0001-01-01T00:00:00Z\",\"generatorURL\":\"http://prometheus-k8s-0:9090/graph?g0.expr=up%7Bjob%3D%22non-k8s%2Fnode_export%22%7D+%3D%3D+0\\u0026g0.tab=1\"},{\"status\":\"firing\",\"labels\":{\"alertname\":\"node-up\",\"instance\":\"10.88.88.180:9591\",\"job\":\"non-k8s/node_export\",\"prometheus\":\"monitoring/k8s\",\"severity\":\"1\",\"team\":\"node\"},\"annotations\":{\"summary\":\"10.88.88.180:9591 已停止运行超过 15s！\"},\"startsAt\":\"2020-08-05T01:18:12.81696489Z\",\"endsAt\":\"0001-01-01T00:00:00Z\",\"generatorURL\":\"http://prometheus-k8s-1:9090/graph?g0.expr=up%7Bjob%3D%22non-k8s%2Fnode_export%22%7D+%3D%3D+0\\u0026g0.tab=1\"},{\"status\":\"firing\",\"labels\":{\"alertname\":\"node-up\",\"instance\":\"10.88.88.181:9591\",\"job\":\"non-k8s/node_export\",\"prometheus\":\"monitoring/k8s\",\"severity\":\"1\",\"team\":\"node\"},\"annotations\":{\"summary\":\"10.88.88.181:9591 已停止运行超过 15s！\"},\"startsAt\":\"2020-08-05T01:17:42.81696489Z\",\"endsAt\":\"0001-01-01T00:00:00Z\",\"generatorURL\":\"http://prometheus-k8s-0:9090/graph?g0.expr=up%7Bjob%3D%22non-k8s%2Fnode_export%22%7D+%3D%3D+0\\u0026g0.tab=1\"}],\"groupLabels\":{\"job\":\"non-k8s/node_export\"},\"commonLabels\":{\"alertname\":\"node-up\",\"job\":\"non-k8s/node_export\",\"prometheus\":\"monitoring/k8s\",\"severity\":\"1\",\"team\":\"node\"},\"commonAnnotations\":{},\"externalURL\":\"http://alertmanager-main-1:9093\",\"version\":\"4\",\"groupKey\":\"{}:{job=\\\"non-k8s/node_export\\\"}\"}\n";
        JSONObject jsonObject = JSON.parseObject(s);
        String alerts = jsonObject.getString("alerts");
        JSONArray jsonArray = JSON.parseArray(alerts);
        StringBuffer sBuffer = new StringBuffer();
        jsonArray.forEach(jsonobejct -> arrayIdToString((JSONObject)jsonobejct,sBuffer));
        System.out.println(sBuffer.toString());
//        if(Boolean.parseBoolean(PropUtil.getproval("alert.server.msg.able"))){
//            System.out.println(1);
//        } else {
//            System.out.println(2);
//        }

    }

    private static StringBuffer arrayIdToString(JSONObject jsonobejct,StringBuffer sBuffer) {
        String status = (String) jsonobejct.get("status");
        if(status.equals("firing")){
            sBuffer.append("【报警】");
        } else if(status.equals("resolved")){
            sBuffer.append("【恢复】");
        }
        String date = (String) jsonobejct.get("startsAt");
        sBuffer.append("【").append(date.substring(0,19)).append("】");
        JSONObject annotations = (JSONObject) jsonobejct.get("annotations");
        return sBuffer.append(annotations);
    }


    private String handresp(){
        //{"resp":{"status":0,"message":"请求成功","body":{"buz_status":0,"buz_message":"业务处理成功"},"event_id":"0ac98c13c2e14aff9d6413192b1bbb3d"}}
        Map<String,Object> map = new HashMap<>();
        map.put("status",0);
        map.put("message","请求成功");
        Map<String,Object> map1 = new LinkedHashMap<>();
        map1.put("buz_status",0);
        map1.put("buz_message","处理成功");
        map.put("body",map1);
        Map<String,Object> map2 = new LinkedHashMap<>();
        map2.put("resp",map);
        return JSON.toJSONString(map2);
    }

    private String handrespFail(String msg){
        //{"resp":{"status":0,"message":"请求成功","body":{"buz_status":0,"buz_message":"业务处理成功"},"event_id":"0ac98c13c2e14aff9d6413192b1bbb3d"}}
        Map<String,Object> map = new HashMap<>();
        map.put("status",0);
        map.put("message","请求成功");
        Map<String,Object> map1 = new LinkedHashMap<>();
        map1.put("buz_status",-1);
        map1.put("buz_message","处理失败:"+msg);
        map.put("body",map1);
        Map<String,Object> map2 = new LinkedHashMap<>();
        map2.put("resp",map);
        return JSON.toJSONString(map2);
    }

    /**
     * 获取body参数
     */
    private String getBody(FullHttpRequest request) {
        ByteBuf buf = request.content();
        return buf.toString(CharsetUtil.UTF_8);
    }

    /**
     * 发送的返回值
     */
    private void send(ChannelHandlerContext ctx, String context, HttpResponseStatus status) {
        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, Unpooled.copiedBuffer(context, CharsetUtil.UTF_8));
        response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8");
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    }

    /*
     * 建立连接时，返回消息
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("连接的客户端地址:" + ctx.channel().remoteAddress());
        ctx.writeAndFlush("客户端" + InetAddress.getLocalHost().getHostName() + "成功与服务端建立连接！ ");
        super.channelActive(ctx);
    }

}
